import store from '@/store'
import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import {getToken, getTimeStamp, removeTimeStamp} from '@/utils/auth'

const instance = axios.create({
    baseURL:process.env.VUE_APP_BASEURL
})

instance.interceptors.request.use(
    config=>{
        //判断是否有token
        const token = getToken()
        if(token){
            //判断token是否超时
            if(Date.now() - getTimeStamp()  > 30*60*1000){
                store.dispatch('user/logout')
                // removeTimeStamp()
                Message.info('登录超时，请重新登录')
                router.push('/login')
                setTimeout(() => {
                    console.clear()
                }, 10);
                return Promise.reject(new Error('token 超时'))
            }
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error =>{
        return Promise.reject(error)
    }
)
instance.interceptors.response.use(
    response =>{
        // console.log(response.data);
        const {success,message} = response.data
        if(success){
            // Message.success(message)
            return response.data
        }else{
            Message.error(message)
            return Promise.reject(new Error(message))
        }
    },
    error =>{
        console.dir(error);
        //判断token是否失效
        const bool = error.response && error.response.data && error.response.data.code === 10002
        //失效则退出登录,跳转到登录页面
        if(bool){
            store.dispatch('user/logout')
            Message.info('登录过期，请重新登录')
            router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
        }
        return Promise.reject(error)
    }
)

export default instance